from PyQt5.QtWidgets import QAbstractItemView
from PyQt5.QtGui import QStandardItem
from PyQt5.QtGui import QStandardItemModel
import json


# 人员选择部分的执行内容，所有需要执行人员选择操作的页面都可以继承此类
class PeopleSelect:
    def __init__(self, ui, mainWindow):
        self.ui = ui
        self.session = mainWindow.session
        self.mainWindow = mainWindow
        self.model = QStandardItemModel(0, 6)
        self.model.setHorizontalHeaderLabels(['警员编号', '姓名', '职位', '警衔', '部门', '是否被选择'])
        self.ui.view_toBeSelected.setEditTriggers(QAbstractItemView.NoEditTriggers)  # 设置表格不可编辑
        self.ui.view_toBeSelected.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置表格只可整行选择
        self.ui.view_toBeSelected.verticalHeader().hide()
        self.ui.view_toBeSelected.setModel(self.model)

        # 定义右侧已经被选择的人员表
        # 右侧已经被选择的人员表中多包含一列，为该行在左侧未被选择人员表中的行数，方便数据恢复，通常设为隐藏列
        self.selected = QStandardItemModel(0, 6)
        self.selected.setHorizontalHeaderLabels(['警员编号', '姓名', '职位', '警衔', '部门', '原始行数'])
        self.ui.view_selected.setEditTriggers(QAbstractItemView.NoEditTriggers)  # 设置表格不可编辑
        self.ui.view_selected.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置表格只可整行选择
        self.ui.view_selected.verticalHeader().hide()
        self.ui.view_selected.setModel(self.selected)

        # 信号和槽连接
        self.ui.edit_name.textChanged.connect(self.searchPeople)
        self.ui.edit_id.textChanged.connect(self.searchPeople)
        self.ui.box_post.currentIndexChanged.connect(self.searchPeople)
        self.ui.box_title.currentIndexChanged.connect(self.searchPeople)
        self.ui.box_department.currentIndexChanged.connect(self.searchPeople)
        self.ui.btn_add.clicked.connect(self.addPeople)
        self.ui.btn_remove.clicked.connect(self.removePeople)
        self.ui.btn_removeAll.clicked.connect(self.removeAllPeople)

    def loadData(self):
        response = self.session.get(self.mainWindow.url + '/admin/police/data?page=1&limit=1000000')
        text = json.loads(response.text)
        dataList = text['data']

        # 加载数据时先清空原有的选项，防止重复加载
        self.ui.box_post.clear()
        self.ui.box_title.clear()
        self.ui.box_department.clear()

        self.clearSelected()

        # 定义 Set，用于记录不同的警员职位
        postList = {''}

        # 定义 Set，用于记录不同的警员头衔
        titleList = {''}

        # 定义 Set，用于记录不同的警员部门
        departmentList = {''}

        no = 0
        for item in dataList:
            postList.add(str(item['post']))
            titleList.add(str(item['title']))
            departmentList.add(str(item['dept_name']))
            item11 = QStandardItem(str(item['code']))
            item12 = QStandardItem(item['name'])
            item13 = QStandardItem(item['post'])
            item14 = QStandardItem(item['title'])
            item15 = QStandardItem(item['dept_name'])
            item16 = QStandardItem(str(0))
            self.model.setItem(no, 0, item11)
            self.model.setItem(no, 1, item12)
            self.model.setItem(no, 2, item13)
            self.model.setItem(no, 3, item14)
            self.model.setItem(no, 4, item15)
            self.model.setItem(no, 5, item16)
            no = no + 1

        for post in postList:
            self.ui.box_post.addItem(post, post)
        for title in titleList:
            self.ui.box_title.addItem(title, title)
        for department in departmentList:
            self.ui.box_department.addItem(department, department)

        self.ui.view_toBeSelected.hideColumn(5)
        self.ui.view_selected.hideColumn(5)

    def searchPeople(self):
        id = self.ui.edit_id.text()
        name = self.ui.edit_name.text()
        post = self.ui.box_post.currentText()
        title = self.ui.box_title.currentText()
        department = self.ui.box_department.currentText()
        for i in range(self.model.rowCount()):
            if (self.model.item(i, 5).text() != "0"):
                continue
            if id != "":
                if (self.model.item(i, 0).text().find(id) == -1):
                    self.ui.view_toBeSelected.setRowHidden(i, True)
                    continue
            if name != "":
                if (self.model.item(i, 1).text().find(name) == -1):
                    self.ui.view_toBeSelected.setRowHidden(i, True)
                    continue
            if post != "":
                if (self.model.item(i, 2).text() != post):
                    self.ui.view_toBeSelected.setRowHidden(i, True)
                    continue
            if title != "":
                if (self.model.item(i, 3).text() != title):
                    self.ui.view_toBeSelected.setRowHidden(i, True)
                    continue
            if department != "":
                if (self.model.item(i, 4).text() != department):
                    self.ui.view_toBeSelected.setRowHidden(i, True)
                    continue
            self.ui.view_toBeSelected.setRowHidden(i, False)

    def addPeople(self):
        # 获取左侧表中被选中的警员
        list = self.ui.view_toBeSelected.selectedIndexes()
        if (len(list) <= 0):
            return
        i = 0

        # 遍历被选中的警员，把该警员从左侧表中隐藏，添加到右侧表中
        while i < len(list):
            n = self.selected.rowCount()
            row = list[i].row()
            # 警员编号
            item11 = QStandardItem(list[i].data())
            i = i + 1
            # 姓名
            item12 = QStandardItem(list[i].data())
            i = i + 1
            # 职位
            item13 = QStandardItem(list[i].data())
            i = i + 1
            # 警衔
            item14 = QStandardItem(list[i].data())
            i = i + 1
            # 部门
            item15 = QStandardItem(list[i].data())
            i = i + 1
            # 隐藏列
            item16 = QStandardItem(str(row))
            self.selected.setItem(n, 0, item11)
            self.selected.setItem(n, 1, item12)
            self.selected.setItem(n, 2, item13)
            self.selected.setItem(n, 3, item14)
            self.selected.setItem(n, 4, item15)
            self.selected.setItem(n, 5, item16)
            self.ui.view_selected.hideColumn(5)

            # 被选中的警员只会从左侧表中被隐藏，不会被删除
            # 设置该警员状态为已经被选择
            self.ui.view_toBeSelected.hideRow(row)
            self.model.setItem(row, 5, QStandardItem(str(1)))
        self.ui.view_toBeSelected.clearSelection()
        self.ui.view_selected.clearSelection()

    def removePeople(self):
        # 获取右侧表中被选择的警员
        list = self.ui.view_selected.selectedIndexes()
        if (len(list) <= 0):
            return
        i = 0

        # 记录要从右侧删除的警员的行数位置，先记录，再从后到前删除，这样不会产生列表行位置变化的问题
        deleteRowList = []

        while (i < len(list)):
            row = list[i].row()
            deleteRowList.append(row)
            # 使用右侧表中”原始行数“一项的记录可以快速恢复左侧表的显示
            # 设置该警员状态为未被选择
            self.ui.view_toBeSelected.setRowHidden(int(self.selected.item(row, 5).text()), False)
            self.model.setItem(int(self.selected.item(row, 5).text()), 5, QStandardItem(str(0)))

            i = i + 5

        i = len(deleteRowList) - 1

        # 从后向前移除，不会产生行数变化的问题
        while (i >= 0):
            self.selected.removeRow(int(deleteRowList[i]))
            i = i - 1
        self.ui.view_toBeSelected.clearSelection()
        self.ui.view_selected.clearSelection()

    def removeAllPeople(self):
        # 把左侧表所有警员的隐藏状态设置为False，并清空右侧表
        # 设置左侧表所有警员状态都是未被选择
        for i in range(0, self.model.rowCount()):
            self.ui.view_toBeSelected.setRowHidden(i, False)
            self.model.setItem(i, 5, QStandardItem(str(0)))
        self.selected.clear()
        self.selected.setHorizontalHeaderLabels(['警员编号', '姓名', '职位', '警衔', '部门', '原始行数'])
        self.ui.view_selected.hideColumn(5)
        self.ui.view_toBeSelected.clearSelection()
        self.ui.view_selected.clearSelection()

    # 检查是否有警员被选择
    def checkSelected(self):
        return not self.selected.rowCount() == 0

    # 获得选中警员的 id
    def getSelectedIds(self):
        if not self.checkSelected():
            return []
        ids = []
        for i in range(0, self.selected.rowCount()):
            ids.append(self.selected.item(i, 0).text())
        return ids

    def getSelectedNames(self):
        if not self.checkSelected():
            return []
        names = []
        for i in range(0, self.selected.rowCount()):
            names.append(self.selected.item(i, 1).text())
        return names

    # 获取被选中警员的姓名
    def getSelectedNames(self):
        if not self.checkSelected():
            return None
        names = []
        for i in range(0, self.selected.rowCount()):
            names.append(self.selected.item(i, 1).text())
        return names

    def clearSelected(self):
        self.selected.clear()
        self.selected.setHorizontalHeaderLabels(['警员编号', '姓名', '职位', '警衔', '部门', '原始行数'])
        self.ui.view_toBeSelected.clearSelection()
        self.ui.view_selected.clearSelection()
